<template>
  <div class="order-management">
    <!-- 搜索表单 -->
    <a-card title="筛选条件" style="margin-bottom: 20px">
      <a-form layout="inline" :model="queryParams">
        <a-form-item label="订单ID">
          <a-input v-model:value="queryParams.id" placeholder="请输入订单ID" />
        </a-form-item>
        <a-form-item label="审核状态">
          <a-select v-model:value="queryParams.auditStatus" style="width: 150px">
            <a-select-option :value="undefined">全部</a-select-option>
            <a-select-option :value="0">待审核</a-select-option>
            <a-select-option :value="1">已审核</a-select-option>
            <a-select-option :value="2">打回</a-select-option>
            <a-select-option :value="3">完成</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-table
      :columns="columns"
      :data-source="orderList"
      :pagination="pagination"
      :loading="loading"
      rowKey="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, text, record }">
        <!-- 审核状态 -->
        <template v-if="column.dataIndex === 'auditStatus'">
          <a-tag :color="statusColorMap[text]">
            {{ statusTextMap[text] }}
          </a-tag>
        </template>
        <!-- 创建时间 -->
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'updateTime'">
          {{ dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <!-- 操作列 -->
        <template v-if="column.dataIndex === 'action'">
          <a-button type="link" v-if="record.auditStatus !==1 && record.auditStatus !==3" @click="showEditModal(record)">编辑</a-button>
          <a-button type="link" v-if="record.auditStatus !==1 && record.auditStatus !==3" danger
                    @click="handleDelete(record.id)">删除
          </a-button>
          <a-button v-if="record.auditStatus === 0" type="link" @click="handleAudit(record.id,1)">
            审核
          </a-button>
          <a-button v-if="record.auditStatus === 4" type="link" @click="handleAudit(record.id,0)">
            提交
          </a-button>
          <a-button v-if="record.auditStatus !== 3" type="link" @click="handleAudit(record.id,4)">
            打回
          </a-button>
          <a-button v-if="record.auditStatus === 1" type="link" @click="handleFinish(record.id,3)">
            完成
          </a-button>
        </template>

        <!-- 公司名称显示 -->
        <template v-if="column.dataIndex === 'companyId'">
          {{ companyList.find(c => c.id === text)?.companyName || text }}
        </template>
      </template>
    </a-table>


    <!-- 新增/编辑模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      @cancel="resetForm"
    >
      <a-form :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="购入数量" required>
          <a-input-number v-model:value="formState.quantityPurchased" :min="1" />
        </a-form-item>
        <a-form-item label="公司" required>
          <a-select v-model:value="formState.companyId" @focus="loadCompanies">
            <a-select-option
              v-for="company in companyList"
              :key="company.id"
              :value="company.id"
            >
              {{ company.companyName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="总金额" required>
          <a-input-number
            v-model:value="formState.totalMoney"
            :min="0"
            :precision="2"
            :step="0.1"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  addOrdersUsingPost,
  auditOrdersUsingPost,
  deleteOrdersUsingPost,
  finishOrdersUsingPost,
  listOrdersPageUsingPost,
  updateOrdersUsingPost
} from '@/api/ordersController.ts'
import { listUserVoByPageUsingPost1 } from '@/api/companyController.ts'
import dayjs from 'dayjs'

// 状态定义
const orderList = ref([])
const companyList = ref([])
const loading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref('新建订单')
const isEdit = ref(false)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true
})

// 查询参数
const queryParams = reactive({
  id: undefined,
  auditStatus: undefined
})

// 表单状态
const formState = reactive({
  id: undefined,
  quantityPurchased: undefined,
  companyId: undefined,
  totalMoney: undefined
})

// 状态映射
const statusTextMap = {
  0: '待审核',
  1: '已审核',
  2: '打回',
  3: '完成',
  4: '未提交'
}

const statusColorMap = {
  0: 'orange',
  1: 'green',
  2: 'red',
  3: 'blue',
  4: 'gray'
}

// 表格列配置
// 列配置简化为：
const columns = [
  { title: '订单ID', dataIndex: 'id' },
  { title: '购入数量', dataIndex: 'quantityPurchased' },
  { title: '公司', dataIndex: 'companyId' },
  { title: '总金额', dataIndex: 'totalMoney' },
  { title: '审核状态', dataIndex: 'auditStatus' },
  { title: '创建时间', dataIndex: 'createTime' },
  { title: '操作', dataIndex: 'action' }
]

// 生命周期钩子
onMounted(async () => {
  const results = await Promise.allSettled([
    loadOrders(),
    loadCompanies()
  ])

  results.forEach((result) => {
    if (result.status === 'rejected') {
      console.error('加载失败:', result.reason)
    }
  })
})

// 加载订单数据
const loadOrders = async () => {
  try {
    loading.value = true
    const params = {
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    }
    const res = await listOrdersPageUsingPost(params)
    orderList.value = res.data.data.records
    pagination.total = res.data.total
  } catch (error) {
    message.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 加载公司数据
const loadCompanies = async () => {
  try {
    const res = await listUserVoByPageUsingPost1({ pageSize: 100 })
    companyList.value = res.data.data.records
  } catch (error) {
    message.error('公司数据加载失败')
  }
}

// 表格分页/排序变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadOrders()
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  loadOrders()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(queryParams).forEach(key => {
    queryParams[key] = undefined
  })
  loadOrders()
}

// 显示新增模态框
const showAddModal = () => {
  modalVisible.value = true
  isEdit.value = false
  modalTitle.value = '新建订单'
}

// 显示编辑模态框
const showEditModal = (record) => {
  modalVisible.value = true
  isEdit.value = true
  modalTitle.value = '编辑订单'
  Object.assign(formState, record)
}

// 提交表单
const handleModalOk = async () => {
  try {
    if (isEdit.value) {
      await updateOrdersUsingPost(formState)
    } else {
      await addOrdersUsingPost(formState)
    }
    message.success('操作成功')
    resetForm()
    loadOrders()
  } catch (error) {
    message.error('操作失败')
  }
}

// 删除订单
const handleDelete = async (id) => {
  try {
    await deleteOrdersUsingPost({ id })
    message.success('删除成功')
    loadOrders()
  } catch (error) {
    message.error('删除失败')
  }
}

// 审核订单
const handleAudit = async (id, status) => {
  try {
    await auditOrdersUsingPost({ id, auditStatus: status })
    message.success('审核成功')
    loadOrders()
  } catch (error) {
    message.error('审核失败')
  }
}

// 完成订单
const handleFinish = async (id, status) => {
  try {
    await finishOrdersUsingPost({ id, auditStatus: status })
    message.success('已完成')
    loadOrders()
  } catch (error) {
    message.error('操作失败')
  }
}

// 重置表单
const resetForm = () => {
  modalVisible.value = false
  Object.keys(formState).forEach(key => {
    formState[key] = undefined
  })
}
</script>

<style scoped>
.order-management {
  padding: 20px;
}
</style>
